package com.gientech.loancenter.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gientech.loancenter.entity.LoanApply;
import com.gientech.loancenter.mq.enity.LoanMessage;
import com.gientech.loancenter.repository.LoanApplyMapper;
import com.gientech.loancenter.rpc.CustomerCenterMapper;
import com.gientech.loancenter.service.LoanApplyService;
import com.gientech.loancommon.core.LoanStatus;
import com.gientech.loancommon.core.LoanTopic;
import com.gientech.loancommon.vo.ResponseResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.kie.api.KieBase;
import org.kie.api.runtime.KieSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Map;

@Service
public class LoanApplyServiceImpl extends ServiceImpl<LoanApplyMapper, LoanApply> implements LoanApplyService {

    @Autowired
    private CustomerCenterMapper customerCenterMapper;

    @Autowired
    private KieBase kieBase;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 贷款申请
     * @param loanApply
     * @return
     */
    @Override
    public ResponseResult loanApply(LoanApply loanApply) {
        ResponseResult result = customerCenterMapper.getById(loanApply.getCustomerId());
        if(result.getData()!=null){
            Map<String,Object> map = JSONObject.parseObject(JSON.toJSONString(result.getData()));
            loanApply.setCustomerName(map.get("name").toString());
        }
        //设置日期格式
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
        String applyNumber = "AN"+ LocalDateTime.now().format(fmt);
        loanApply.setApplyNumber(applyNumber);
        KieSession kieSession = kieBase.newKieSession();
        // 将order对象插入工作内存
        kieSession.insert(loanApply);

        // 匹配对象
        // 激活规则，由drools框架自动进行规则匹配。若匹配成功，则执行
        kieSession.fireAllRules();

        // 关闭会话
        kieSession.dispose();
        //贷款人申请
        loanApply.setStatus(LoanStatus.APPLY);
        loanApply.setCreateTime(new Date());
        this.save(loanApply);
        return new ResponseResult();
    }

    /**
     * 贷款审批查询
     * @return
     */
    @Override
    public ResponseResult pageLoanApply() {
        // 查询条件
        QueryWrapper<LoanApply> queryWrapper = new QueryWrapper<>();
        queryWrapper.inSql("status","1,2,3");
        // 分页参数: 页码:2, 单页大小：10
        Page<LoanApply> page = new Page<>(1,10);
        // 分页查询, 多个条件为and的关系
        Page<LoanApply> result = this.page(page, queryWrapper);
        return new ResponseResult(result);
    }

    /**
     * 贷款审核
     * @param id
     * @param status
     * @return
     * @throws Exception
     */
    @Override
    public ResponseResult doCheck(Long id, Integer status){
        LoanApply loanApply = this.getById(id);
        Integer oldStatus = loanApply.getStatus();
        loanApply.setStatus(status);
        this.updateById(loanApply);
        //发送消息
        sendMessage(loanApply.getCustomerId(),oldStatus,loanApply.getStatus());
        return new ResponseResult(loanApply);
    }

    /**
     * 贷款查询
     * @param status
     * @return
     */
    @Override
    public ResponseResult pageLoanByStatus(Integer status) {
        // 查询条件
        QueryWrapper<LoanApply> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status",status);
        // 分页参数: 页码:2, 单页大小：10
        Page<LoanApply> page = new Page<>(1,10);
        // 分页查询, 多个条件为and的关系
        Page<LoanApply> result = this.page(page, queryWrapper);
        return new ResponseResult(result);
    }

    /**
     * 放款
     * @param id
     * @param releaseAmount
     * @return
     * @throws Exception
     */
    @Override
    public ResponseResult doRelease(Long id, Float releaseAmount) {
        LoanApply loanApply = this.getById(id);
        int oldStatus = loanApply.getStatus();
        loanApply.setReleaseAmount(releaseAmount);
        loanApply.setReleaseTime(new Date());
        loanApply.setStatus(LoanStatus.RELEASE_AMOUNT);
        this.updateById(loanApply);
        //发送消息
        sendMessage(loanApply.getCustomerId(),oldStatus,loanApply.getStatus());
        return new ResponseResult(loanApply);
    }

    /**
     * 推送消息到MQ
     * @param customerId
     * @param status
     * @throws Exception
     */
    @Async
    public void sendMessage(Long customerId,int oldStatus, int status) {
        LoanMessage loanMessage = new LoanMessage(customerId,oldStatus,status);
        ResponseResult result = customerCenterMapper.getById(customerId);
        if(result.getData()!=null){
            Map<String,Object> map = JSONObject.parseObject(JSON.toJSONString(result.getData()));
            loanMessage.setName(map.get("name").toString());
            loanMessage.setMobile(map.get("mobile").toString());
        }
        KieSession kieSession = kieBase.newKieSession();
        // 将order对象插入工作内存
        kieSession.insert(loanMessage);

        // 匹配对象
        // 激活规则，由drools框架自动进行规则匹配。若匹配成功，则执行
        kieSession.fireAllRules();

        // 关闭会话
        kieSession.dispose();
        rocketMQTemplate.convertAndSend(LoanTopic.LOAN_MESSGAE,JSON.toJSONString(loanMessage));
    }
}
